package com.LeetCode.StackAndHeap;

import org.junit.Test;

import java.util.Stack;

/**
 * 计算器 表达式求值
 */
public class Calculater {

    public int calculate(String s) {
        Stack<Integer> stack = new Stack<>();
        int num = 0;
        char sign = '+';
        char[] chars = s.toCharArray();
        int len = chars.length;
        int res = 0;
        for(int i = 0; i<len; i++){
            char cur = chars[i];
            if(cur >= '0'){
                num = num * 10 + cur - '0';
            }
            if((cur < '0' && cur !=' ') || i == len - 1){
                switch (sign){
                    case '+' : stack.push(num); break;

                    case '-' : stack.push(-num); break;

                    case '*' : stack.push(stack.pop() * num); break;

                    case '/' : stack.push((int) stack.pop() / num); break;
                }
                sign = cur;
                num = 0;
            }
        }
        while(!stack.isEmpty()){
            res += stack.pop();
        }
        return res;
    }

    @Test
    public void test(){
        System.out.println(calculate("1+1 / 2"));
    }

}
